<?php

namespace common\components;

use Yii;
use yii\base\Component;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "lookup".
 *
 * @property integer $id
 * @property string $type
 * @property string $name
 * @property integer $code
 * @property string $comment
 * @property integer $active
 * @property integer $sort_order
 * @property integer $created_at
 * @property integer $updated_at
 */
class Lookup extends Component {

    private static $_items = [];
    public $modelClass = '\common\models\Lookup';

    /**
     * Returns the items for the specified type.
     * @param string item type (e.g. 'PostStatus').
     * @return array item names indexed by item code. The items are order by their sort_order values.
     * An empty array is returned if the item type does not exist.
     */
    public static function items($type) {
        if (!isset(self::$_items[$type]))
            self::loadItems($type);
        return self::$_items[$type];
    }

    /**
     * Returns the item name for the specified type and code.
     * @param string the item type (e.g. 'PostStatus').
     * @param integer the item code (corresponding to the 'code' column value)
     * @return string the item name for the specified the code. False is returned if the item type or code does not exist.
     */
    public static function item($type, $code) {
        if (!isset(self::$_items[$type]))
            self::loadItems($type);
        return isset(self::$_items[$type][$code]) ? self::$_items[$type][$code] : false;
    }

    /**
     * Loads the lookup items for the specified type from the database.
     * @param string the item type
     */
    private static function loadItems($type) {
        self::$_items[$type] = array();
          $models = '\common\models\Lookup'::find()
          ->where([
          'type' => $type,
          'active' => 1,
          ])
          ->orderBy('sort_order')
          ->all();
         
        foreach ($models as $model)
            self::$_items[$type][$model->code] = $model->name;
    }

}
